import { BillStateError } from './../filter/billstate.filter';
import { ApplyBill, ApplyBillSubmitDto } from './../entity/recall.entity';
import {
  Body,
  Controller,
  Del,
  Get,
  Inject,
  Param,
  Post,
  Put,
} from '@midwayjs/core';
@Controller('/recall')
export class Recall {
  @Inject()
  dB;
  @Get('/browser')
  async browse() {
    console.log('XXXX');
    // return new Date().getTime();
    const a = [
      { name: 'zhangsan', age: 10 },
      { name: 'lisi', age: 11 },
    ];
    return a;
  }
  @Post('/browseByCondition')
  async browseByCondition(@Body() condition) {
    /* {
        yyy:"zh",
       }
     */
    console.log(condition);
    const content = [
      { name: 'zhangsan', age: 10 },
      { name: 'zhaoliu', age: 10 },
      { name: 'lisi', age: 11 },
      { name: 'wanwu', age: 11 },
    ];
    const results = content.filter(xxx => xxx.name.includes(condition.yyy));
    console.log(results);
    return results;
  }

  //  总览 开放4+1 接口
  @Post('/query')
  async query() {
    return this.dB.applyBills;
  }
  //   新增
  @Post('/insert')
  async insert(@Body() applyBill: ApplyBill) {
    this.dB.applyBills.push(applyBill);
    return true;
  }
  //   删除
  @Del('/remove/:id')
  async removeById(@Param('id') targetId: number) {
    console.log(targetId, typeof targetId);
    const index = this.dB.applyBills.findIndex(x => x.id === targetId);
    console.log(index);
    if (index >= 0) {
      this.dB.applyBills.splice(index, 1);
    }
    return true;
  }
  //   查看
  //    ts 标注类型后 1 阅读源代码 清除 2  框架认识 3 写代码提示性好
  @Get('/find/:id')
  async findbyId(@Param('id') id: number) {
    const applyBill = this.dB.applyBills.find(e => e.id === id);
    return applyBill;
  }
  //   修改
  //   懒人做法
  @Put('/modify')
  async modify(@Body() applyBill: ApplyBill) {
    console.log(applyBill);
    const index = this.dB.applyBills.findIndex(e => e.id === applyBill.id);
    console.log(index);
    if (index >= 0) {
      this.dB.applyBills[index] = applyBill;
      //   this.dB.applyBIlls.splice(index, 1, applyBill);
    }
    return true;
  }
  // 勤劳的做法 Patch Put
  @Put('/modify/:id')
  async modifyById(
    @Param('id') id: number,
    @Body() applyBillSubmitDto: ApplyBillSubmitDto
  ) {
    const bill = this.dB.applyBills.find(e => e.id === id);
    if (!bill) {
      throw new BillStateError('修改数据已经过期');
    }
    // bill.company = applyBillSubmitDto.company;
    // bill.job = applyBillSubmitDto.job;
    Object.assign(bill, applyBillSubmitDto);
    return true;
  }
}
